package org.znxs.znxsojsandbox.controller;


import org.springframework.web.bind.annotation.*;
import org.znxs.znxsojsandbox.model.ExecuteCodeRequest;
import org.znxs.znxsojsandbox.model.ExecuteCodeResponse;
import org.znxs.znxsojsandbox.service.JavaDockerCodeSandbox;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/")
public class SayHelloController {


    @Resource
    private JavaDockerCodeSandbox javaDockerCodeSandbox;


    @GetMapping("/say")
    public String sayHello() {
        return "helo";
    }

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";


    @GetMapping("/exec")
    public void exec() {
        String code = "public class Main{public static void  main(String[]args){;System.out.println(Integer.valueOf(args[0])+Integer.valueOf(args[1]));}}";


        List<String> inputList = new ArrayList<String>();
        inputList.add("1 2");
        inputList.add("2 3");
        inputList.add("3 4");

        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest(code, "java", inputList);
        try {
            ExecuteCodeResponse executeCodeResponse = javaDockerCodeSandbox.executeCode(executeCodeRequest);
            System.out.println(executeCodeResponse);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @GetMapping("/docker")
    public void processDocker() {
        String codePath = "X:\\user\\desktop\\project\\znxsOJ\\znxs-code-sandbox\\src\\main\\resources\\sandbox\\testFiles";
//        dockerJavaRun.dockerRun(codePath);
    }

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request) {
        if (executeCodeRequest == null) {
            throw new RuntimeException("请求参数为空");
        }
        // 验证请求
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            throw new RuntimeException("无权限");
        }
        return javaDockerCodeSandbox.executeCode(executeCodeRequest);
    }


}
